package org.pidan.basic.multiThread;

/**
 * {@code @description}: 死锁演示
 * {@code @author}: huangyuxin
 * {@code @date}: 2023-12-12
 */
public class SiSuo {

    public static class Obj1 {
    }

    public static class Ob2 {
    }


    public static class SynAddRunnable implements Runnable {

        Obj1 object1;

        Ob2 object2;

        int a, b;

        boolean flag;

        public SynAddRunnable(Obj1 object1, Ob2 object2, int a, int b, boolean flag) {
            this.object1 = object1;
            this.object2 = object2;
            this.a = a;
            this.b = b;
            this.flag = flag;
        }


        @Override
        public void run() {

            try {

                if (flag) {
                    synchronized (object1) {
                        Thread.sleep(100);
                        synchronized (object2) {
                            System.out.println("我到object2了" + a + b);
                        }
                    }
                } else {
                    synchronized (object2) {
                        Thread.sleep(100);
                        synchronized (object1) {
                            System.out.println("我到object1了" + a + b);
                        }
                    }
                }

            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }


    public static void main(String[] args) {
        Obj1 obj1 = new Obj1();
        Ob2 ob2 = new Ob2();

        Thread thread = new Thread(new SynAddRunnable(obj1, ob2, 1, 2, true));
        thread.setName("no1");
        thread.start();

        new Thread(new SynAddRunnable(obj1, ob2, 2, 3, false));
        thread.setName("no2");
        thread.start();


    }

}
